<script setup lang="ts" name="HomeView">
import { ref, computed, watch, onMounted } from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import { compListConfig, layoutLineInfo } from '@/components/layout/config'
import { computeCurrIndex } from '@/utils/common'
import { useCompStore  } from '@/stores/compConfig';
import { useLayoutStore  } from '@/stores/layoutConfig';
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router';
import FormList from '@/components/common/FormList.vue'

const list = ref(compListConfig);
const router = useRouter();
const compStore = useCompStore();
const { currCompName, currCompIndex, compInfo, compList, compForm } = storeToRefs(compStore);
const layoutStore = useLayoutStore();
const { currLayout } = storeToRefs(layoutStore);

onMounted(() => {
  handleClear()
  // todo... 请求默认数据
  layoutStore.resetLayout(4)
  resetEditorStyle();
})
// 编辑区组件
const layoutList = computed(() => {
  return list.value.slice(0, currLayout.value)
})
const layoutLine = computed(() => {
  return layoutLineInfo.filter((item:any) => item.type === currLayout.value)
})
// 组件库拖拽
type sn = string | null
let currentComponents = ref<sn[]>([null, null, null, null, null, null])
const onEnd = (event: any) => {
  list.value = compListConfig;
  const currIndex = computeCurrIndex({ x: event.originalEvent.x, y: event.originalEvent.y })
  if(currIndex === -1) return
  const currComp = event.clonedData.comp
  if(currentComponents.value.includes(currComp)) return
  currentComponents.value[currIndex] = currComp
  compStore.updateCompList('add', {index: currIndex, comp: currComp});
  currCompIndex.value = -1
}
// 编辑区拖拽
let startIndex = ref(0)
let startComp = ref<string | null>(null)
const onConStart = (event: any) => {
  startIndex.value = computeCurrIndex({ x: event.originalEvent.x, y: event.originalEvent.y });
  startComp.value = currentComponents.value[startIndex.value]
}
const onConEnd = (event: any) => {
  list.value = compListConfig;
  const endIndex = computeCurrIndex({ x: event.originalEvent.x, y: event.originalEvent.y })
  if(endIndex === -1) return
  const endComp = currentComponents.value[endIndex];
  currentComponents.value[endIndex] = startComp.value
  currentComponents.value[startIndex.value] = endComp
  compStore.updateCompList('replace',{ index: startIndex.value, endIndex});
  currCompIndex.value = -1
}
// 编辑区选中
const formList = ref()
const currForm = ref()
const selectComp = (index:number) => {
  currCompIndex.value = currCompIndex.value === index ? -1 : index
  currCompName.value = currentComponents.value[currCompIndex.value]
  if(compInfo.value) {
    currForm.value = { ...compInfo.value.data, ...compInfo.value.style }
    formList.value = compForm.value;
  }
}
// 布局切换
const changeLayout = (val: number) => {
  currLayout.value = val
  layoutStore.resetLayout(currLayout.value)
}
// 预览
const handlePreview = () => {
  const routeData = router.resolve({ path: '/preview' });
  window.open(routeData.href, '_blank');
}
// 清空
const handleClear = () => {
  currentComponents.value = [null, null, null, null, null , null]
  currCompIndex.value = -1
  currCompName.value = null
  compStore.updateCompList('clear', {index: 0});
}
// 删除
const handleDelete = () => {
  compStore.updateCompList('delete', {index: currCompIndex.value});
  currentComponents.value[currCompIndex.value] = null;
  currCompIndex.value = -1
  currCompName.value = null
}
watch(
  currLayout, 
  (newVal, oldVal) => {
    if(newVal < oldVal) {
      currentComponents.value[5] = null
      if(newVal === 4) {
        currentComponents.value[4] = null
      }
    }
  },
)
// 面板折叠
const collapse_l = ref(false)
const collapse_r = ref(false)
const collapse_l_t = ref(false)
const collapse_l_b = ref(false)
const size = ref(71.875)
const translate = ref('');
let scaleFactor = ref(1)
watch([collapse_l, collapse_r],() => {
  if (collapse_l.value && collapse_r.value) {
    size.value = 97
    translate.value = 'translate(200px, 100px)'
  } else if (!collapse_l.value && !collapse_r.value) {
    size.value = 71.875
    translate.value = 'translate(30px, 46px)'
  } else {
    size.value = 84
    translate.value = 'translate(130px, 56px)'
  }
  scaleFactor.value = parseFloat(size.value.toString()) / 71.875;
})
const conRef = ref()
const resetEditorStyle = () => {
  const con_width = conRef.value?.clientWidth;
  const cons_height = conRef.value?.clientHeight;
  if(!con_width || !cons_height) return
  scaleFactor.value = con_width / 1440
  const translateX = con_width * 0.5 - 1920 * size.value / 100 * 0.5;
  const translateY = cons_height * 0.5 - 1080 * size.value / 100 * 0.5;
  translate.value = 'translate(' + translateX + 'px, ' + translateY + 'px)'
  console.log('translate', translate.value, scaleFactor.value)
}
</script>

<template>
  <header>
    <div class="header_title">交通物流一张图配置</div>
    <div class="header_oper">
      <div class="oper_l">
        <div class="oper_btn" @click="handlePreview">
          <img src="@/assets/icon/eye.svg" alt="">
          <span>预览</span>
        </div>
        <div class="oper_btn">
          <img src="@/assets/icon/save.svg" alt="">
          <span>保存</span>
        </div>
        <div class="oper_btn">
          <img src="@/assets/icon/send.svg" alt="">
          <span>发布</span>
        </div>
      </div>
      <div class="line_c"></div>
      <div class="oper_r">
        <div class="oper_btn">
          <img src="@/assets/icon/close.svg" alt="">
          <span>关闭</span>
        </div>
      </div>
    </div>
  </header>
  <main>
    <div :class="['container_l', { retract: collapse_l }]">
      <div :class="['con_l_box', { active: collapse_l_t }]">
        <div class="con_l_title" @click="collapse_l_t = !collapse_l_t">
          <span>一张图布局</span>
          <img src="@/assets/home/arrow-down.svg" alt="">
        </div>
        <div class="con_l_c">
          <div class="l_c_war">
            <img src="@/assets/icon/info.svg" alt="">
            <span>请选择布局后再拖动组件</span>
          </div>
          <div :class="['l_layout', { active: currLayout === 4 }]" @click="changeLayout(4)">
            <span>四布局</span>
            <img src="@/assets/home/layout-4.png" alt="">
          </div>
          <div :class="['l_layout', { active: currLayout === 6 }]" @click="changeLayout(6)">
            <span>六布局</span>
            <img src="@/assets/home/layout-6.png" alt="">
          </div>
        </div>
      </div>
      <div :class="['con_l_box', { active: collapse_l_b }]">
        <div class="con_l_title" @click="collapse_l_b = !collapse_l_b">
          <span>组件库</span>
          <img src="@/assets/home/arrow-down.svg" alt="">
        </div>
        <div class="con_l_c">
          <div class="l_c_war">
            <img src="@/assets/icon/info.svg" alt="">
            <span>请选择布局后再拖动组件</span>
          </div>
          <VueDraggable v-model="list" @end="onEnd" target=".com_box">
            <div class="com_box">
              <div v-for="item in list" :key="item.id" class="com_item">
                <img :src="`src/assets/home/comp-${item.comp}.png`" alt="">
                <span>{{ item.label }}</span>
              </div>
            </div>
          </VueDraggable>
        </div>
      </div>
    </div>
    <div class="container_c" id="container_c" ref="conRef">
      <div class="editor_c" id="bff_editor" :style="{ transform: 'scale(' + scaleFactor + ')' + translate}">
        <div class="editor_header" id="editor_header">
           <HeaderComp />
        </div>
        <VueDraggable v-model="list" :onStart="onConStart" :onEnd="onConEnd">
          <div :class="['item', 'item' + currLayout, {'select': index === currCompIndex}]" v-for="(item, index) in layoutList" :key="index">
            <div class="item_bg" v-if="!currentComponents[index]"></div>
            <component v-else :is="currentComponents[index]" :ref="'item' + index" @click="selectComp(index)" v-model="compList[index]"></component>
          </div>
        </VueDraggable>
        <div 
          v-for="item in layoutLine"
          :key="item.id"
          :class="item.class" 
          :id="item.id" 
          v-lineDrag="{drag: item.id, layout: currLayout}"
        ></div>
      </div>
    </div>
    <div :class="['container_r', { retract: collapse_r }]">
      <FormList :formList="formList" :data="currForm" :comp="currCompName"/>
    </div>
    <div :class="['collapse','left',{ active: collapse_l}]" @click="collapse_l = !collapse_l">
      <img src="@/assets/home/arrow-left.svg" alt="" />
    </div>
    <div :class="['collapse','right',{ active: collapse_r}]" @click="collapse_r = !collapse_r">
      <img src="@/assets/home/arrow-right.svg" alt="" />
    </div>
  </main>
</template>
<style scoped lang="scss">
@import '@/style/home.scss';
</style>
